package auth

import (
	"beluga/models"
	"beluga/tools"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

//LoginController 登录控制器
type LoginController struct {
	beego.Controller
}

//LoginUser 用户
type LoginUser struct {
	UserName   string `orm:"unique;size(32)" form:"username"  valid:"Required;MaxSize(20);MinSize(6)"`
	Password   string `orm:"size(128)" form:"password" valid:"Required;MaxSize(20);MinSize(6)"`
	RePassword string `orm:"-" form:"repassword" valid:"Required"`
}

//Get 登录页面
func (c *LoginController) Get() {
	c.Data["pageName"] = "登录"
	c.TplName = "auth/login.tpl"
}

//Post 登录请求
func (c *LoginController) Post() {
	o := orm.NewOrm()
	o.Using("default")
	username := c.GetString("username")
	password := c.GetString("password")
	check := models.User{UserName: username}
	err := o.Read(&check, "UserName")
	rc := RequestCode{}
	if err == orm.ErrNoRows {
		//查询结果为空， 写入数据
		rc.Code = 3
		rc.Msg = "用户不存在"
	} else if err == orm.ErrMissPK {
		rc.Code = 1
		rc.Msg = "找不到 pk"
	} else {
		checkPassword := check.Password
		checkActive := check.IsActive
		verify, _ := tools.PasswordVerify(password, checkPassword)
		if checkActive == false {
			rc.Code = 4
			rc.Msg = "登录失败，用户已禁用"
		} else if verify == true {
			rc.Code = 0
			rc.Msg = "登录成功,1秒后跳转"
			//beego.Informational(check.Id)
			sessionkey := beego.AppConfig.String("SessionKey")
			sessionexpire, _ := beego.AppConfig.Int("SessionExpire")
			sessionencode := tools.SessionEncode(sessionkey)
			expireDate := tools.HalfAMonth()
			c.Ctx.SetCookie("beluga", sessionencode, sessionexpire)
			insertSession := new(models.Session)
			insertSession.User = &check
			insertSession.Value = sessionencode
			insertSession.Expire = expireDate
			o.Insert(insertSession)
		} else if verify == false {
			rc.Code = 2
			rc.Msg = "密码不正确，请重新输入"
		} else {
			rc.Code = 5
			rc.Msg = "为止错误，请联系管理员"
		}

	}
	//f
	c.Data["json"] = rc
	c.ServeJSON()
	c.Ctx.Redirect(302, "/")
}
